package com.piece.core.framework.util.string;

import com.piece.core.framework.enums.PieceDFunction;
import com.piece.core.framework.enums.PieceSFunction;
import com.piece.core.framework.util.object.BeanUtil;
import java.lang.invoke.SerializedLambda;
import java.util.WeakHashMap;

public class LambdaUtil {

    private static final WeakHashMap<String, SerializedLambda> cache = new WeakHashMap();

    public static <T> SerializedLambda resolve(PieceDFunction<T, ?> func) {
        return cache.computeIfAbsent(func.getClass().getName(), (key) -> (SerializedLambda) BeanUtil.exec(func, "writeReplace", new Object[0]));
    }

    public static <R> SerializedLambda resolve(PieceSFunction<R> func) {
        return cache.computeIfAbsent(func.getClass().getName(), (key) -> (SerializedLambda) BeanUtil.exec(func, "writeReplace", new Object[0]));
    }

    public static <P> String getMethodName(PieceDFunction<P, ?> func) {
        return resolve(func).getImplMethodName();
    }

    public static <T> String getFieldName(PieceDFunction<T, ?> func) throws IllegalArgumentException {
        return BeanUtil.getFieldName(getMethodName(func));
    }

    private static void checkLambdaTypeCanGetClass(int implMethodKind) {
        if (implMethodKind != 5 && implMethodKind != 6) {
            throw new IllegalArgumentException("该lambda不是合适的方法引用");
        }
    }
}
